package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.domain.Image;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.IdentityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zr 2024/2/29
 */
@Slf4j
@RestController
@Api(tags = "文件管理")
@RequestMapping("/wx")
public class FileController {
    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws Exception {
        String uploadFlag = fileService.upload(file, file.getOriginalFilename());
        if (uploadFlag == "上传成功") {
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.error("上传成功");
        }
    }

    /**
     * 文件删除
     *
     * @param file
     * @return
     */
    @PostMapping("/file/del")
    @ApiOperation(value = "文件删除")
    public AjaxResult del(@RequestPart("file") MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        System.err.println(originalFilename);
        // 格式：src/avatar/NtfS2dFs3XoR373e936f3c2fc4e051cfd661406c3320.jpg
        String delFlag = fileService.del("src/avatar/NtfS2dFs3XoR373e936f3c2fc4e051cfd661406c3320.jpg");
        if (delFlag == "删除成功") {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 获取文件url
     *
     * @param
     * @return
     */
    @GetMapping("/file/getUrl")
    @ApiOperation(value = "获取文件url")
    public AjaxResult getUrl(String[] images) throws Exception {
        List<String> imgList = Arrays.asList(images);
        List<URL> urls = imgList.stream().map(item -> {
            URL url = fileService.getUrl(item);
            return url;
        }).collect(Collectors.toList());

        return AjaxResult.success(urls);
    }
}
